/*
 * @Author: your name
 * @Date: 2021-12-09 19:04:03
 * @LastEditTime: 2021-12-11 11:36:39
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \12.9作业\demo\index.ts
 */


interface Listener {
    (...args:any[]):void;
  } 
  interface Events {
    // your code
    [propName:string]:Listener[]
  }
  
  class EventEmitter {
    // your code 定义私有属性 events
    private preson:Events={}
    on (eventName: string, listener: Listener) {
      // your code
      if(!this.preson[eventName]){
          this.preson[eventName]=[listener]
      }else{
          this.preson[eventName].push(listener)
      }
    }
  
    emit (eventName: string, ...args: any[]) {
      // your code
    //   console.log(eventName);
      this.preson[eventName]&&this.preson[eventName].map(event=>event(...args))
    //   console.log(this.preson);
      
    }
    // 删除
    off (eventName: string, listener: Listener) {
      // your code
      if(this.preson[eventName]){
        this.preson[eventName].forEach((item,index)=>{
          if(item===listener){
            this.preson[eventName].splice(index,1)
          }
        })
      }
    }
    // 只执行一次
    once (eventName: string, listener: Listener) {
      // your code
      const on:Listener=(...args)=>{
        console.log(args);
        
        listener(...args)
        this.off(eventName,on)
      }
      this.on(eventName,on)
    }
  
  }
  
  // 调用示例
  const req = new EventEmitter()
  
  const handler = (sum:any) => {
    console.log(sum)
  }
  
  req.on('data', handler)
  
  req.once('data', handler)
  
  req.off('data', handler)
  
  req.emit('data',"郭家俊大傻子")
  req.emit('data',"郭家俊大傻子")  